//引入express模块
const express = require('express');
//引入rp模块
// const rp = require('request-promise-native');
//引入ejs模块
// const ejs = require('ejs');
//引入sha1加密
const sha1 = require('sha1');
// 引入reply模块
const reply = require('../reply/index');
//引入wechat模块
const Wechat = require('../wechat/wechat');

const {
    url,
    appID,
    appsecret,
    touser,
    template_id
} = require('../connfig');
const axios = require('axios')
    // const con = require('../public/js/echats/BloodGlucose.js');
const {
    homeDatas,
    homeBottom,
    fithessDatas,
    echatsDatas
} = require('../api')
    //获取Router
const Router = express.Router;
//创建路由对象
const router = new Router();
//创建实例对象
const wechatApi = new Wechat();
//页面路由
router.get('/search', async(req, res) => {
    //获取随机字符串
    let num = Math.random() + '';
    let noncestr = num.split('.')[1];
    //获取时间戳
    const timestamp = Date.now();
    //获取票据
    const {
        ticket
    } = await wechatApi.fetchTicket()
    console.log(ticket);
    //组合四个参数
    const arr = [
        `jsapi_ticket=${ticket}`,
        `noncestr=${noncestr}`,
        `timestamp=${timestamp}`,
        `url=${url}/search`
    ]

    //进行字典排序，以&符连接
    const str = arr.sort().join('&');
    console.log(str);
    //进行sha1加密
    const signature = sha1(str);
    // console.log(signature);
    res.render('search', {
        signature,
        noncestr,
        timestamp,
    })
});
//首页页面内容
router.get('/home', async(req, res) => {

    res.render('home', {
        homeDatas,
        homeBottom,
    })
});
router.get("/", async(req, res) => {
    // console.log(JSON.parse(sessionStorage.getItem("data")));
    const code = req.query.code;
    const ACCESS_TOKEN_RES = await axios({
        url: 'https://api.weixin.qq.com/sns/oauth2/access_token',
        params: {
            appid: appID,
            secret: appsecret,
            code: code,
            grant_type: 'authorization_code'
        }
    })
    const {
        access_token,
        openid
    } = ACCESS_TOKEN_RES.data;
    const USERINFO_RES = await axios({
        url: 'https://api.weixin.qq.com/sns/userinfo',
        params: {
            access_token: access_token,
            secret: appsecret,
            openid: openid,
            lang: 'zh_CN'
        }
    })
    var mineDatas = USERINFO_RES.data.openid;
    res.render('long', {
        homeDatas,
        homeBottom,
        mineDatas
    })
});
router.get("/mine", async(req, res) => {
    // const code = req.query.code;
    // const ACCESS_TOKEN_RES = await axios({
    //     url: 'https://api.weixin.qq.com/sns/oauth2/access_token',
    //     params: {
    //         appid: appID,
    //         secret: appsecret,
    //         code: code,
    //         grant_type: 'authorization_code'
    //     }
    // })
    // const {
    //     access_token,
    //     openid
    // } = ACCESS_TOKEN_RES.data;
    // const USERINFO_RES = await axios({
    //     url: 'https://api.weixin.qq.com/sns/userinfo',
    //     params: {
    //         access_token: access_token,
    //         secret: appsecret,
    //         openid: openid,
    //         lang: 'zh_CN'
    //     }
    // })
    // var mineDatas = USERINFO_RES.data.openid;
    res.render('mine', {
        homeBottom,
        // mineDatas
    })
});
router.get("/fitness", async(req, res) => {
    res.render('fitness', {
        fithessDatas,
        homeBottom,
        echatsDatas
    })

});
//渲染登录页面
router.get("/long", async(req, res) => {
    const code = req.query.code;
    const ACCESS_TOKEN_RES = await axios({
        url: 'https://api.weixin.qq.com/sns/oauth2/access_token',
        params: {
            appid: appID,
            secret: appsecret,
            code: code,
            grant_type: 'authorization_code'
        }
    })
    const {
        access_token,
        openid
    } = ACCESS_TOKEN_RES.data;
    const USERINFO_RES = await axios({
        url: 'https://api.weixin.qq.com/sns/userinfo',
        params: {
            access_token: access_token,
            secret: appsecret,
            openid: openid,
            lang: 'zh_CN'
        }
    })
    var mineDatas = USERINFO_RES.data.openid;
    console.log(mineDatas);
    res.render('long', {
        mineDatas
    })
});
//渲染注册页面
router.get("/login", async(req, res) => {

    res.render('login', {})
});
//渲染绑定列表页面
router.get("/bindinglist", async(req, res) => {

    res.render('bindingList', {})
});
//渲染添加绑定页面
router.get("/addbinding", async(req, res) => {

    res.render('addBinding', {})
});
//渲染血糖页面
router.get("/bloodglucose", async(req, res) => {
    res.render('bloodglucose', {})
});
//渲染血氧页面
router.get("/oxygenlevel", async(req, res) => {
    res.render('oxygenLevel', {

    })
});
//渲染体温页面
router.get("/temperature", async(req, res) => {
    res.render('tempeRature', {

    })
});
//渲染心电页面
router.get("/ecg", async(req, res) => {
    res.render('ECG', {

    })
});
//渲染个人信息页面
router.get("/user", async(req, res) => {
    const code = req.query.code;
    const ACCESS_TOKEN_RES = await axios({
        url: 'https://api.weixin.qq.com/sns/oauth2/access_token',
        params: {
            appid: appID,
            secret: appsecret,
            code: code,
            grant_type: 'authorization_code'
        }
    })
    const {
        access_token,
        openid
    } = ACCESS_TOKEN_RES.data;
    const USERINFO_RES = await axios({
        url: 'https://api.weixin.qq.com/sns/userinfo',
        params: {
            access_token: access_token,
            secret: appsecret,
            openid: openid,
            lang: 'zh_CN'
        }
    })
    var mineDatas = USERINFO_RES.data;
    console.log(mineDatas);
    res.render('user', {
        mineDatas
    })
});
//渲染绑定账号页面
router.get("/bindingaccounts", async(req, res) => {

    res.render('bindingaccounts', {})
});
//渲染详情页面
router.get("/detailpage", async(req, res) => {

    const {
        access_token
    } = await wechatApi.fetchAccessToken();

    function e() {
        var data = JSON.stringify({
            "touser": "ofXDe6hPaX3VuPiPBR2_8eiOzoNU",
            "template_id": "oTzEaUU2L-PtRbwqhPFCBeD4_fesfhSxZk9EZO2JLfQ",
            "url": "http://awkvty.natappfree.cc/detailpage?Authorization=eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6Ijg0ZWY3MmY2LWM1MjMtNDVjMy1hNDZmLWJiZjVmYWY3ZjBlOCJ9.JqKUguG5zGWXzHSwmNAYvoJ3H1gEL0zxZmkRpTaoRCALWF5NQgLLzZQ9fil-gTETl0DHRzO-4a3_JkGhXMtK8g",
            "data": {
                "first": {
                    "value": "恭喜你购买成功！",
                    "color": "#173177"
                },
                "keyword1": {
                    "value": "巧克力",
                    "color": "#173177"
                },
                "keyword2": {
                    "value": "39.8元",
                    "color": "#173177"
                },
                "keyword3": {
                    "value": "2014年9月22日",
                    "color": "#173177"
                },
                "remark": {
                    "value": "欢迎再次购买！",
                    "color": "#173177"
                }
            }
        });

        var config = {
            method: 'post',
            url: `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${access_token}`,
            headers: {
                'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)',
                'Content-Type': 'application/json',
                'Accept': '*/*',
                'Host': 'api.weixin.qq.com',
                'Connection': 'keep-alive'
            },
            data: data
        };


        axios(config)
            .then(function(response) {
                console.log(JSON.stringify(response.data));
            })
            .catch(function(error) {
                console.log(error);
            });
    }
    res.render('detailPage', {
        access_token,
    })
});
//渲染历史体检页面
router.get("/historylist", async(req, res) => {
    res.render('historyList', {

    })
});
//渲染列表详情页面
router.get("/historypage", async(req, res) => {
    res.render('historyPage', {

    })
});
//渲染周报页面
router.get("/weeklynewspaper", async(req, res) => {
    const code = req.query.code;
    const ACCESS_TOKEN_RES = await axios({
        url: 'https://api.weixin.qq.com/sns/oauth2/access_token',
        params: {
            appid: appID,
            secret: appsecret,
            code: code,
            grant_type: 'authorization_code'
        }
    })
    const {
        access_token,
        openid
    } = ACCESS_TOKEN_RES.data;
    const USERINFO_RES = await axios({
        url: 'https://api.weixin.qq.com/sns/userinfo',
        params: {
            access_token: access_token,
            secret: appsecret,
            openid: openid,
            lang: 'zh_CN'
        }
    })
    var mineDatas = USERINFO_RES.data.openid;
    console.log(mineDatas);
    res.render('weeklyNewspaper', {
        mineDatas
    })
});
router.use(reply());
module.exports = router